<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>小小画板</title>
    <style>
        body,div,header,main{margin:0;padding:0;}
        html,body,.container{height:100%;}
        .container{background: #eee;overflow: hidden;}
        header{height:10%;}
        header>input{height:90%;width:33%;vertical-align: top;}
        header>a{font-size: 40px;}
        main{height:90%;}
        canvas{background: #fff;cursor: pointer;}
    </style>
</head>
<body>
    <div class="container">
        <header>
            <input type="color" id="mycolor">-*
            <input type="range" min="1" max="50" value="1" id="myrange">
            <a href="javascript:;" id="clear">清空</a>
        </header>
        <main>
            <canvas></canvas>
        </main>
    </div>
</body>
<script>
    //1.获取画布对象
    var canvas=document.querySelector("canvas");
    //2.获取绘图上下文(画笔)
    var ctx=canvas.getContext("2d");//three.js,webGL
    //3.获取父元素的尺寸
    var main=document.querySelector("main");
    //4.设置画布的宽高
    var w=canvas.width=main.offsetWidth;
    var h=canvas.height=main.offsetHeight;
    //5.给画布设置鼠标事件
    var isDown=false;
    var isd=false
    ctx.lineCap='round';
    canvas.onmousedown=function(e){
       
        ctx.beginPath();//开始路径(开始绘制)
        ctx.moveTo(e.pageX-canvas.offsetLeft,e.pageY-canvas.offsetTop);//画笔移动到某个位置
        isDown=true;
       isd=true;
         if(tu&&isd){
            ctx.clearRect(e.pageX-canvas.offsetLeft-50,e.pageY-canvas.offsetTop-50,100,100)
        }
    }
    canvas.onmouseup=function(){
        isDown=false;
        isd=false
        
    }
    canvas.onmousemove=function(e){
       
        if(tu)isDown=false
        if(isDown){
            ctx.lineTo(e.pageX-canvas.offsetLeft,e.pageY-canvas.offsetTop);//画到这个点
            ctx.stroke();//真实的去画
        }
        if(tu&&isd){
            ctx.clearRect(e.pageX-canvas.offsetLeft-50,e.pageY-canvas.offsetTop-50,100,100)
        }
       
    }

    var mycolor=document.querySelector("#mycolor");
    var myrange=document.querySelector("#myrange");
    var clear=document.querySelector("#clear");
    // clear.onclick=function(){
    //     ctx.clearRect(0,0,w,h);//清除画布(x,y,w,h)
    // }
    mycolor.onchange=function(){
        ctx.strokeStyle=this.value;//线的样式
    }

    myrange.onchange=function(){
        ctx.lineWidth=this.value;//宽度
    }
    // var cl=document.querySelector('#clear');
    var tu=false
    clear.onclick=function(){
        tu=!tu
    }

</script>
</html>